
package com.lmx.persistence.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.URLUtil;
import com.lmx.repoDomain.tmodel.Call;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.Dicttype;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.Task;
import com.lmx.repoDomain.tmodel.business.User;//huibati


/**
 * #{description}
 * 后台通话列表接口
 * @author shen
 * @version 1.00
 */
@Service
@Scope("prototype")
public class CallManageService<T>{
	
	private Log logger = LogFactory.getLog(this.getClass());

    @PersistenceContext
    private EntityManager em;
    
    @Autowired
    protected GenericService dslJpaService;

    /**
     * 获取通话记录列表
     * @param values
     * @return
     */
    public List<Map<String ,Object>> getCallList(Map<String ,Object> values){
    	
		logger.debug("获取通话记录列表");
		
		List<Map<String ,Object>> callList = new ArrayList<Map<String ,Object>>();
		
		String query = "select c from Call c where c.delStatus != 1";
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and c.agent.loginName like '%"+loginName+"%'";
		}
		//任务名
		String taskName = (String)values.get("taskName");
		if(taskName != null && !taskName.isEmpty()){
			query = query + " and c.task.title like '%"+taskName+"%'";
		}
		//创建时间
		String startTime = (String)values.get("startTime"); 
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and c.createTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		query = query +" order by c.createTime desc";
		
		Query qu = (Query) this.em.createQuery(query);
		qu.setMaxResults((int)values.get("size"));
		qu.setFirstResult((int)values.get("pageNum"));
		List resultList = qu.getResultList();
				
		for(int i = 0 ; i < resultList.size() ; i ++){
			Call call = (Call) resultList.get(i);
			Map<String ,Object> callMap = new HashMap<String, Object>();
			
			Long callID = call.getId();
			callMap.put("callID", callID.toString());//通话记录id
			String loginNameStr = "";
			String nameStr = "";
			User user = call.getAgent();
			if(user != null){
				loginNameStr = user.getLoginName();
				nameStr = user.getName();
			}
			callMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			callMap.put("name", nameStr==null?nameStr="":nameStr);//真实姓名
			String taskNameStr = "";
			Task task = call.getTask();
			if(task != null){
				taskNameStr = task.getTitle();
			}
			callMap.put("taskName", taskNameStr==null?taskNameStr="":taskNameStr);//任务名称
			String name = "";
			String phone = "";
			Customer customer = call.getCustomer();
			if(customer != null){
				name = customer.getName();
				phone= customer.getPhone();
			}
			callMap.put("customerName", name==null?name="":name);//客户名称
			callMap.put("phone", phone==null?phone="":phone);//客户电话
			String directionStr = "";
			Short direction = call.getDirection();
			if(direction != null){
				directionStr = ICommonConstants.DIRECTION.values()[direction].label();
			}
			callMap.put("direction", directionStr==null?directionStr="":directionStr);//呼叫方向
			String callingNumber = call.getCallingNumber();
			callMap.put("callingNumber", callingNumber==null?callingNumber="":callingNumber);//呼入电话
			String calledNumber = call.getCalledNumber();
			callMap.put("calledNumber", calledNumber==null?calledNumber="":calledNumber);//呼出电话
			String duration = "0:0:0";
			Integer durationInt = call.getDuration();
			if(durationInt != null){
				duration = CommonUtil.timeChange(durationInt);
			}
			callMap.put("duration", duration==null?duration="0:0:0":duration);//通话时长
			String statusStr = "";
			Dicttype status = call.getStatus();
			if(status != null){
				statusStr = status.getTypename();
			}
			callMap.put("statusStr", statusStr==null?statusStr="":statusStr);//通话状态
			String operationStr = "";
			Dicttype operation = call.getOperation();
			if(status != null){
				operationStr = operation.getTypename();
			}
			callMap.put("operationStr", operationStr==null?operationStr="":operationStr);//动作
			String failedCauseStr = "";
			Short failedCause = call.getFailedCause();
			if(failedCause != null){
				failedCauseStr = ICommonConstants.CALLFAILCAUSE.values()[failedCause].label();
			}
			callMap.put("failedCauseStr", failedCauseStr==null?failedCauseStr="":failedCauseStr);//通话失败原因
			Double cost = call.getCost();
			callMap.put("cost", cost==null?cost=0.0:cost);//通话费用
			String createTime = "";
			Integer createTimeInt =  call.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			callMap.put("createTime", createTime);//创建时间
			String updateTime = "";
			Integer updateTimeInt =  call.getUpdateTime();
			if(updateTimeInt != null){
				updateTime = CommonUtil.integetTimeForString(updateTimeInt);
			}
			callMap.put("updateTime",updateTime);//修改时间
			
			callList.add(callMap);
		}
		
        return callList;
    }
    
    /**
     * 获取通话记录列表总条数
     * @param values
     * @return
     */
    public int getCallListCount(Map<String ,Object> values){
    	
		logger.debug("获取通话记录列表总条数");
		
		String query = "select count(c.id) from Call c where c.delStatus != 1";
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and c.agent.loginName like '%"+loginName+"%'";
		}
		//任务名
		String taskName = (String)values.get("taskName");
		if(taskName != null && !taskName.isEmpty()){
			query = query + " and c.task.title like '%"+taskName+"%'";
		}
		//创建时间
		String startTime = (String)values.get("startTime"); 
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and c.createTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		int count = (int)(long)this.em.createQuery(query)
    			.getSingleResult();
		
        return count;
    }
    
    /**
     * 获取通话记录详情
     * @param values
     * @return
     */
    public Map<String ,Object> getCall(Long callID){
    	
			logger.debug("获取通话记录详情");
		
			Call call = this.em.find(Call.class, callID);
			Map<String ,Object> callMap = new HashMap<String, Object>();
			
			callMap.put("callID", callID.toString());//通话记录id
			String loginNameStr = "";
			String nameStr = "";
			User user = call.getAgent();
			if(user != null){
				loginNameStr = user.getLoginName();
				nameStr = user.getName();
			}
			callMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			callMap.put("name", nameStr==null?nameStr="":nameStr);//姓名
			String taskNameStr = "";
			String desc = "";
			Task task = call.getTask();
			if(task != null){
				taskNameStr = task.getTitle();
				desc = task.getDesc();
			}
			callMap.put("taskName", taskNameStr==null?taskNameStr="":taskNameStr);//任务名称
			callMap.put("desc", desc==null?desc="":desc);//任务描述
			String name = "";
			String phone = "";
			Customer customer = call.getCustomer();
			if(customer != null){
				name = customer.getName();
				phone= customer.getPhone();
			}
			callMap.put("customerName", name==null?name="":name);//客户名称
			callMap.put("phone", phone==null?phone="":phone);//客户电话
			String directionStr = "";
			Short direction = call.getDirection();
			if(direction != null){
				directionStr = ICommonConstants.DIRECTION.values()[direction].label();
			}
			callMap.put("direction", directionStr==null?directionStr="":directionStr);//呼叫方向
			String callingNumber = call.getCallingNumber();
			callMap.put("callingNumber", callingNumber==null?callingNumber="":callingNumber);//呼入电话
			String calledNumber = call.getCalledNumber();
			callMap.put("calledNumber", calledNumber==null?calledNumber="":calledNumber);//呼出电话
			String beginTime = "";
			Integer beginTimeInt =  call.getCreateTime();
			if(beginTimeInt != null){
				beginTime = CommonUtil.integetTimeForString(beginTimeInt);
			}
			callMap.put("beginTime", beginTime);//开始时间
			String endTime = "";
			Integer endTimeInt =  call.getUpdateTime();
			if(endTimeInt != null){
				endTime = CommonUtil.integetTimeForString(endTimeInt);
			}
			callMap.put("endTime",endTime);//结束时间
			String duration = "0:0:0";
			Integer durationInt = call.getDuration();
			if(durationInt != null){
				duration = CommonUtil.timeChange(durationInt);
			}
			callMap.put("duration", duration==null?duration="0:0:0":duration);//通话时长
			String statusStr = "";
			Dicttype status = call.getStatus();
			if(status != null){
				statusStr = status.getTypename();
			}
			callMap.put("statusStr", statusStr==null?statusStr="":statusStr);//通话状态
			String operationStr = "";
			Dicttype operation = call.getOperation();
			if(status != null){
				operationStr = operation.getTypename();
			}
			callMap.put("operationStr", operationStr==null?operationStr="":operationStr);//动作
			String failedCauseStr = "";
			Short failedCause = call.getFailedCause();
			if(failedCause != null){
				failedCauseStr = ICommonConstants.CALLFAILCAUSE.values()[failedCause].label();
			}
			callMap.put("failedCauseStr", failedCauseStr==null?failedCauseStr="":failedCauseStr);//通话失败原因
			String voiceRecording = call.getVoiceRecording();
			callMap.put("voiceRecording", voiceRecording==null?voiceRecording="":URLUtil.getInstance().getResource()+voiceRecording);//通话录音url
			Double cost = call.getCost();
			callMap.put("cost", cost==null?cost=0.0:cost);//通话费用
			String createTime = "";
			Integer createTimeInt =  call.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			callMap.put("createTime", createTime);//创建时间
			String updateTime = "";
			Integer updateTimeInt =  call.getUpdateTime();
			if(updateTimeInt != null){
				updateTime = CommonUtil.integetTimeForString(updateTimeInt);
			}
			callMap.put("updateTime",updateTime);//修改时间
			String remark = call.getRemark();
			callMap.put("remark", remark==null?remark="":remark);//备注
		
        return callMap;
    }
}
